from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate

class GetTokenView(APIView):
    """
    自定义视图，支持通过 GET 请求获取 JWT 令牌
    实际上，这只是一个包装器，将 GET 请求转发到 TokenObtainPairView
    """
    def get(self, request):
        # 从 GET 参数中获取用户名和密码
        username = request.GET.get('username')
        password = request.GET.get('password')

        if not username or not password:
            return Response(
                {"detail": "用户名和密码是必需的"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 验证用户
        user = authenticate(username=username, password=password)
        if user is None:
            return Response(
                {"detail": "无效的用户名或密码"},
                status=status.HTTP_401_UNAUTHORIZED
            )

        # 创建令牌
        refresh = RefreshToken.for_user(user)

        return Response({
            'refresh': str(refresh),
            'access': str(refresh.access_token),
        })

class GetRefreshTokenView(APIView):
    """
    自定义视图，支持通过 GET 请求刷新 JWT 令牌
    实际上，这只是一个包装器，将 GET 请求转发到 TokenRefreshView
    """
    def get(self, request):
        # 从 GET 参数中获取刷新令牌
        refresh_token = request.GET.get('refresh')

        if not refresh_token:
            return Response(
                {"detail": "刷新令牌是必需的"},
                status=status.HTTP_400_BAD_REQUEST
            )

        try:
            # 验证并刷新令牌
            refresh = RefreshToken(refresh_token)

            return Response({
                'access': str(refresh.access_token),
            })
        except Exception as e:
            return Response(
                {"detail": "无效的刷新令牌"},
                status=status.HTTP_401_UNAUTHORIZED
            )
